package cn.jinjimi.app.modules.notify;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import cn.jinjimi.base.util.GsonUtils;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.URLUtil;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.framework.helper.annotation.EventTraceParam;
import cn.jinjimi.app.AppContext;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.EventDataField;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.bean.ChannelId;
import cn.jinjimi.app.modules.notify.notifications.NotificationBuilder;
import cn.jinjimi.app.modules.notify.notifications.PushArticleDTO;
import cn.jinjimi.app.modules.notify.notifications.PushDTO;
import cn.jinjimi.app.modules.notify.notifications.PushProductDTO;
import cn.jinjimi.app.modules.notify.notifications.PushUpdateDTO;
import cn.jinjimi.app.main.activity.PersonalPhotoActivity;
import cn.jinjimi.app.main.activity.RouteActivity;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by zhenhua on 16/6/3.
 */
public class NotificationDispatcher {

    public static final String TAG = "PushDispatcher";

    /* 通用推送消息 */
    public static final String FLAG_ACTION = "cn.jinjimi.sixapp.MESSAGE";

    /* 形象照上传状态 */
    public static final String PHOTO_UPLOAD_STATE_ACTION = "cn.jinjimi.sixapp.PHOTOUPLOAD_STATE";

    /* 消息模块离线消息 */
    public static final String ACTION_OFFLINE_MSG = "cn.jinjimi.sixapp.IM_OFFLINE_MSG";

    /* 更新消息 */
    public static final String ACTION_UPDATE = "cn.jinjimi.sixapp.UPDATE";

    /* 小米推送action */
    public static final String ACTION_XIAOMI = "com.avos.avoscloud.mi_notification_action";

    public static final String KEY_DATA = "cn.jinjimi.sixapp.Data";

    private static int mRequestCode = NotificationBuilder.CODE_OTHER + 1;

    public static final int REQ_PHOTO_UPLOAD_STATE_ACTION = 20001;
    public static final int REQ_MESSAGE_OFFLINE = 20002;
    public static final int REQ_MESSAGE = 0;

    public static void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equalsIgnoreCase(PHOTO_UPLOAD_STATE_ACTION)) {
            onUploadPhotoAction(context, intent);
        } else if (action.equals(ACTION_UPDATE)) {
            onUpdateApk(context, intent);
        } else {
            onReceive(context, parseNotification(intent));
        }
    }

    private static void onUpdateApk(Context context, Intent intent) {

    }

    public static void onReceive(Context context, PushDTO notification) {

        if (notification == null) {
            return;
        }

        NotificationBuilder builder;

        switch (notification.getType()) {

            case PushDTO.TYPE_IM: //处理消息模块的离线消息推送

                break;
            case PushDTO.TYPE_ARTICLE:
            case PushDTO.TYPE_PRODUCT:
            case PushDTO.TYPE_SIMPLE:
            default:
                int code = getRequestCode();
                builder = new NotificationBuilder(AppContext.getInstance())
                        .alert(notification.alert)
                        .title(notification.title)
                        .code(code)
                        .pending(getPendingIntent(context, notification, code, PendingIntent.FLAG_ONE_SHOT));


                //display message
                sendNotification(context, builder);
                break;
        }

        record(String.valueOf(notification.fromSorce), String.valueOf(notification.type), notification.getUrl(), notification.getSource());
    }


    /**
     * 解析Push对象
     *
     * @param intent
     * @return
     */
    public static PushDTO parseNotification(Intent intent) {
        PushDTO notification = null;
        String data = intent.getStringExtra(KEY_DATA);
        if (data != null) {
            try {
                JSONObject obj = new JSONObject(data);
                switch (obj.getInt("type")) {
                    case PushDTO.TYPE_ARTICLE:
                        notification = GsonUtils.fromJson(data, PushArticleDTO.class);
                        break;
                    case PushDTO.TYPE_PRODUCT:
                        notification = GsonUtils.fromJson(data, PushProductDTO.class);
                        break;
                    case PushDTO.TYPE_UPDATE:
                        notification = GsonUtils.fromJson(data, PushUpdateDTO.class);
                        break;
                    default:
                        notification = GsonUtils.fromJson(data, PushDTO.class);
                        break;
                }
                if (notification != null && StringUtils.isNotEmpty(notification.getUrl())) {
                    notification.setUrl(URLUtil.appendParam(notification.getUrl(), BundleKey.OUTCHANNEL, ChannelId.Push, true));
                }
            } catch (JSONException e) {
                //e.printStackTrace();
            } finally {
                if (notification == null) {
                    notification = GsonUtils.fromJson(data, PushDTO.class);
                    notification.setType(PushDTO.TYPE_SIMPLE);
                }
            }
        }

        return notification;
    }

    /**
     * 统计PUSH到达
     */
    @EventTrace(EventID.APP_PUSH_REACHED)
    private static void record(@EventTraceParam(EventDataField.ParamId) String fromSorce, @EventTraceParam(EventDataField.ParamType) String type,
                               @EventTraceParam(EventDataField.ParamTo) String url, @EventTraceParam(EventDataField.ParamFrom) String source) {
    }

    public static PendingIntent getPendingIntent(Context context, PushDTO notification, int requestCode, int flag) {
        Intent router = new Intent();
        router.setClass(context, RouteActivity.class);
        router.putExtra(KEY_DATA, GsonUtils.toJson(notification));

        return PendingIntent.getActivity(context, requestCode, router, flag);
    }

    /**
     * 上传形象照通知
     */
    @Deprecated
    private static void onUploadPhotoAction(Context context, Intent intent) {

        int state = intent.getIntExtra("state", 0);

        if (state == 0)
            return;

        String alert = null;
        if (state == 1) {
            alert = "正在上传形象照...";
        } else if (state == 2) {
            alert = "形象照上传成功";
        } else if (state == 3) {
            alert = "形象照上传失败";
        }

        Intent remind = new Intent(context, PersonalPhotoActivity.class);
        remind.putExtras(intent);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, REQ_PHOTO_UPLOAD_STATE_ACTION, remind, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationBuilder builder = new NotificationBuilder(context).alert(alert).pending(pendingIntent);
        sendNotification(context, builder);
    }


    /**
     * 将消息发送到通知栏，并响应用户点击发布
     *
     * @param notification
     */
    public static void sendNotification(Context context, NotificationBuilder notification) {

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setSmallIcon(notification.getIcon() == 0 ? R.drawable.logo : notification.getIcon())
                .setContentTitle(TextUtils.isEmpty(notification.getTitle()) ?
                        AppContext.getInstance().getString(R.string.app_name) : notification.getTitle())
                .setContentText(notification.getAlert())
                .setTicker(notification.getAlert())
                .setAutoCancel(true)
                .setContentIntent(notification.getPendingIntent());

        ((NotificationManager) AppContext.getInstance().getSystemService(Context.NOTIFICATION_SERVICE))
                .notify(notification.getCode(), builder.build());
    }

    public static void sendNotification(Context context, String alert, Intent intent) {
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        NotificationBuilder builder = new NotificationBuilder(context).alert(alert).pending(pendingIntent);
        sendNotification(context, builder);
    }

    public static void sendNotification(Context context, String title, String alert, Intent intent) {
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        NotificationBuilder builder = new NotificationBuilder(context).title(title).alert(alert).pending(pendingIntent);
        sendNotification(context, builder);
    }


    /**
     * 播放铃声
     *
     * @param context
     */
    public static void playRingtone(Context context) {

        int volume = ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE))
                .getStreamVolume(AudioManager.STREAM_RING);

        if (volume > 0) {
            Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone ringtone = RingtoneManager.getRingtone(context, sound);
            if (ringtone != null)
                ringtone.play();
        }
    }

    public static int getRequestCode() {
        return ++mRequestCode;
    }
}
